<template>
  <lay-tab
    v-model="tabValue"
    v-if="tabArr && tabArr.length > 0"
    @change="handleChange"
  >
    <lay-tab-item
      v-for="(item, index) in tabArr as any"
      :title="item.name"
      :id="item[keyField]"
      :key="index"
    >
      <template #title>
        {{ getTitle(item) }}
      </template>
      <slot
        name="table"
        v-if="item[keyField] == tabValue"
        v-bind:tabValue="item[keyField]"
        v-bind:treeName="getTitle(item)"
      ></slot>
    </lay-tab-item>
  </lay-tab>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { cloneDeep } from "lodash-es";

type willObjArray = {
  [key: string]: any;
};
const props = defineProps({
  /**
   * 页签点击时需要给客户端宏变量treeKey赋值的属性
   */
  keyField: {
    type: String,
    default: "code",
  },
  /**
   * 显示字段
   * 页签显示名称。如果设置多个则显示格式为：第一个属性（第二个属性）
   */
  displayFields: {
    type: Array,
    default: () => ["name"],
  },
  /**
   * 默认选中值。
   * 默认选中的页签，如果没有设置则选中第一个
   */
  defaultSelect: {
    type: String,
    default: "",
  },
  tabArr: {
    type: Array<willObjArray>,
    default: () => [],
  },
});
const emit = defineEmits(["fetchData"]);
const tabValue = ref("");
const getTitle = (item: any) => {
  const displayFields = cloneDeep(props.displayFields) as any;
  if (displayFields.length > 1) {
    const newArr = displayFields?.shift();

    return `${item[newArr]}(${displayFields.map((_: any) => item[_]).join(",")})`;
  } else {
    return item[displayFields[0]];
  }
};

const handleChange = () => {
  emit("fetchData");
};

watch(
  () => props.tabArr,
  (val) => {
    if (val && val.length > 0) {
      tabValue.value = props.defaultSelect || val[0][props.keyField];
    }
  },
  {
    deep: true,
  },
);
</script>
<style lang="less" scoped></style>
